package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.RelPackageRoute;
import com.ruoyi.system.domain.TourPackage;
import com.ruoyi.system.domain.TourRoute;
import com.ruoyi.system.mapper.TourPackageMapper;
import com.ruoyi.system.service.ITourPackageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TourPackageService implements ITourPackageService {

    @Autowired
    private TourPackageMapper packageMapper;

    @Override
    public List<TourPackage> selectPackages() {
        List<TourPackage> packages = packageMapper.selectPackages();
        return packages;
    }

    @Override
    public TourPackage showPackage(int packageId) {
        return packageMapper.selectPackageDetail(packageId);
    }


    @Override
    public int addPackage(TourPackage tourPackage) {
        int row = packageMapper.insertPackage(tourPackage);
        int packageId = tourPackage.getId();
        List<TourRoute> routes = tourPackage.getRoutes();
        if(routes != null) {
            List<RelPackageRoute> list = getRelList(packageId, routes);
            if(list != null) {
                packageMapper.insertRelPackageRoute(list);
            }
        }
        return row;
    }

    @Override
    public int updatePackage(TourPackage tourPackage) {
        int row = packageMapper.updatePackage(tourPackage);
        int packageId = tourPackage.getId();
        List<TourRoute> routes = tourPackage.getRoutes();
        if(routes != null) {
            List<RelPackageRoute> list = getRelList(packageId, routes);
            packageMapper.delRelPackageRouteById(packageId);
            packageMapper.insertRelPackageRoute(list);
        }
        return row;
    }

    @Override
    public int delPackage(int packageId) {
        int row = packageMapper.delPackage(packageId);
        packageMapper.delRelPackageRouteById(packageId);
        return row;
    }

    private List<RelPackageRoute> getRelList(int packageId, List<TourRoute> routes) {
        if (routes == null) {
            return null;
        }
        int size = routes.size();
        List<RelPackageRoute> list = new ArrayList<>(size);
        for (int i = 0;i < size;i++) {
            list.add(new RelPackageRoute(packageId, routes.get(i).getId(), i+1));
        }
        return list;
    }
}
